<template>
  <div class="login-container">

          <el-form ref="form" :rules="rules" :model="form" label-width="80px" class="login-form">
              <el-tabs  v-model="activeName" @tab-click="handleClick" type="border-card">
                <h2 class="login-title">管理系统</h2>
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input placeholder="请输入密码" v-model="form.password" show-password></el-input>
                </el-form-item>

                <el-tab-pane label="登录" name="login">
                  <el-form-item>
                    <el-checkbox v-model="checked" class="autoCheck">自动登录</el-checkbox>
                    <span @click="clearCookie" class="forgetPwd">忘记密码</span>

                    <el-button type="primary" @click="submitForm('form')">登录</el-button>
                  </el-form-item>
                </el-tab-pane>

                  <el-tab-pane label="注册" name="register">

                    <el-form-item label="确认密码">
                      <el-input placeholder="确认密码" v-model="form.passwordAgain" show-password></el-input>
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="submitForm('form')">注册</el-button>
                    </el-form-item>
                  </el-tab-pane>
            </el-tabs>

           </el-form>

         </div>
</template>

<script>
    import ElementUI from "element-ui";
    import Bus from "./course/bus";
    export default {
        name: "login",
        data () {
          return {
            activeName: 'login',
            checked: true, // 默认选中
            form: {
                username: "",
                password: "",
                passwordAgain:""
               },
            rules: {
                 username: [
                  {required: true, message: "用户名不能为空", trigger: 'blur'},
                  {min: 3, max: 30, message: "用户名3-30位", trigger: 'blur'}
                 ],
                password: [
                  {required: true, message: "密码不能为空", trigger: 'blur'},
                  {min: 3, max: 30, message: "密码3-30位", trigger: 'blur'}
                ]
             }

          }
        },
      methods :{
        handleClick(tab, event) {
          console.log(this.activeName)

          console.log(tab, event);
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                 // console.log(valid) 验证通过为true，有一个不通过就是false
                 if (valid) {
                     //数据准备
                     let activeName = this.activeName;
                     //登录
                     if(activeName=='login'){
                      //去登陆
                       this.$store.dispatch("user/acLogin", this.form).then(() => {
                           // 刷新用户信息界面
                           this.$nextTick(function () {
                             Bus.$emit('toCourseUserRefreshUserAction', '刷新用户信息');
                           });
                           //登录成功后查询学生信息
                          this.findDataByUserId()
                           //登录成功后，跳转到首页页面
                           this.form.username = '';
                           this.form.password = '';
                           //如果是学生用户，默认进入听写列表
                         if(this.$store.state.user.user.userType==1){
                           this.$store.state.course.activeName = 'word_result'
                         }
                           this.$router.push('/course/course');
                       }).catch((e) => {
                         console.log(e)
                       });

                     //注册
                     }else if(activeName=='register'){
                       if(this.form.password != this.form.passwordAgain){
                           ElementUI.Message({
                             message: '两次密码不一致',
                             type: 'warning'
                           });
                         return;
                       }
                       //去注册
                       this.$store.dispatch("user/acRegister", this.form).then((res) => {
                         ElementUI.Message({
                           // message: res.msg,
                           message: '注册成功',
                           type: 'success'
                         });
                         // this.form.username = '';
                         this.form.password = '';
                         this.form.passwordAgain = '';
                         this.activeName = "login";
                       }).catch((e) => {
                         console.log(e)
                       });

                     }

                  } else {
                    console.log('验证失败');
                    return false;
                }
               });
         },

        findDataByUserId(){

          if(this.$store.state.user.user.userType==1){
            const id = this.$store.state.user.user.id
            this.$store.dispatch("sportStudent/findDataById", id).then((res) => {

            }).catch((e) => {
              console.log(e)
            });
          }
        },

        clearCookie(){
          //取消勾线
          this.checked = false;
          // 清空cookie
          this.setCookie('', '', -1) // 修改2值都为空，天数为负1天就好了
        },
        saveCookieData(){
          // 点击登录按钮的时候，判断是否勾选了自动登录（记住密码），对cookie做相应操作
          if (this.checked) {
            // 传入账号名，密码，和保存天数3个参数
            this.setCookie(this.form.username, this.form.password, 7)
          } else {
            // 如果没有选中自动登录，那就清除cookie
            this.setCookie('', '', -1) // 修改2值都为空，天数为负1天就好了
          }
        },
        // 设置cookie
        setCookie (name, pwd, exdays) {
          let exdate = new Date()// 获取时间
          exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays)// 保存的天数
          // 字符串拼接cookie
          window.document.cookie = 'userName' + '=' + name + ';path=/;expires=' + exdate.toGMTString()
          window.document.cookie = 'userPwd' + '=' + pwd + ';path=/;expires=' + exdate.toGMTString()
        },
    // 读取cookie 将用户名和密码回显到input框中
            getCookie () {
              if (document.cookie.length > 0) {
                let arr = document.cookie.split('; ')// 这里显示的格式需要切割一下自己可输出看下
                for (var i = 0; i < arr.length; i++) {
                  let arr2 = arr[i].split('=')// 再次切割
                  // 判断查找相对应的值
                  if (arr2[0] === 'userName') {
                    this.form.username = arr2[1]// 保存到保存数据的地方
                  } else if (arr2[0] === 'userPwd') {
                    this.form.password = arr2[1]
                  }
                }
              }
            },


    },created() {
        // this.getCookie()
      }

    }
</script>

<style scoped>
   .login-form {
             width: 350px;
             margin: 160px auto; /* 上下间距160px，左右自动居中*/
             /*background-color: rgb(255, 255, 255,0.6); !* 透明背景色 *!*/
             background-color: rgb(255, 255, 255); /* 透明背景色 */
             padding: 30px;
             border-radius: 20px; /* 圆角 */
           }
   /*!* 背景 *!*/
   /* .login-container {*/
   /*       position: absolute;*/
   /*        width: 100%;*/
   /*        height: 100%;*/
   /*        background: url("../../assets/login.png");*/
   /*  }*/

      /* 标题 */
      .login-title {
             color: #303133;
            text-align: center;
        }

</style>
